import jwt
from rest_framework.response import Response
from django.conf import settings

# 登录的校验函数
def check_login(func):
    def wrapper(self, request, *args, **kwargs):
        # 校验用户的登录
        # 1、从请求头中获取token
        token = request.headers.get("Authorization")

        # 2、解码token，获取用户的信息
        try:
            # key:用户信息
            payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms=["HS256"])
        except Exception as e:
            print("解码token错误：", e.args)
            return Response({
                "code": 401,
                "msg": "未认证"
            })
        # 3、获取用户的信息
        print("解码出的用户信息：", payload)
        request.uid = payload.get("uid")

        # 4、执行真正的视图类的函数，即装饰的函数
        return func(self, request, *args, **kwargs)
    return wrapper


